import com.google.appengine.api.datastore.*
import static com.google.appengine.api.datastore.FetchOptions.Builder.*

// get url and regex
// get html response
// get content with regex
// get the lastest record
// compare the content with the lastest record
// equal, update the "update_time" of the lastest record
// not equal, add a new entry, and send a mail

def text = new URL("http://www.amazon.cn/%E5%8D%9A%E6%9C%97-%E6%AC%A7%E4%B9%90B-Vitality%E6%B8%85%E4%BA%AE%E5%9E%8B%E7%94%B5%E5%8A%A8%E7%89%99%E5%88%B7D12013/dp/B003J35S2U/").getText("UTF-8")
def regex = ~"priceLarge\">([^<]+)<"
def matcher = text =~ regex
def content = ""
if (matcher.size()){
	content = matcher[0][1]
} else {
	forward "/error.gtpl"
}

def query = new Query("CheckRecord")
query.addSort("check_time", Query.SortDirection.DESCENDING)
PreparedQuery pq = datastore.prepare(query)
def ql = pq.asList(withLimit(1))

def cr = ql[0]
def new_cr = new Entity("CheckRecord")
new_cr.content = content
new_cr.check_time = new Date()

if (cr?.content != content){
	new_cr.age = 1
	new_cr.save()
	mail.send from:"fly.island@gmail.com",
		to:"flyisland@gmail.com",
		subject:"OralB D12013 is $content now!",
		textBody:"OralB D12013 is $content now!"
} else if (cr.age == 1){
	new_cr.age = 2
	new_cr.save()
} else {
	cr.age ++
	cr.check_time = new_cr.check_time
	cr.save()
}

forward "/showCheckRecord.groovy"